import {useState, useEffect} from "react";
import reactLogo from "./assets/react.svg";
import {invoke} from "@tauri-apps/api/core";
import "./App.css";
import {gjsConfig} from "./lib/consts.js";
import grapesjs from "grapesjs";

import 'grapesjs/dist/css/grapes.min.css'
import './css/grapes.min.css'
import './css/component-code-editor.css'
import './css/demos.css'
import './css/grapesjs-preset-webpage-i.css'
import './css/rulers.css'
import './css/grapick.css'
import './css/rte.css'
import './css/tooltip.css'
import './css/custom.css'

function App() {
    const [editor, setEditor] = useState()

    useEffect(() => {
        const editor = grapesjs.init(gjsConfig);

        editor.I18n.addMessages({
            en: {
                styleManager: {
                    properties: {
                        'background-repeat': 'Repeat',
                        'background-position': 'Position',
                        'background-attachment': 'Attachment',
                        'background-size': 'Size',
                    }
                },
            }
        });

        let pn = editor.Panels;
        let modal = editor.Modal;
        let cmdm = editor.Commands;

        // Update canvas-clear command
        cmdm.add('canvas-clear', function () {
            if (confirm('Are you sure to clean the canvas?')) {
                editor.runCommand('core:canvas-clear')
                setTimeout(function () {
                    localStorage.clear()
                }, 0)
            }
        });

        // Add info command
        let mdlClass = 'gjs-mdl-dialog-sm';
        let infoContainer = document.getElementById('info-panel');

        cmdm.add('open-info', function () {
            var mdlDialog = document.querySelector('.gjs-mdl-dialog');
            mdlDialog.className += ' ' + mdlClass;
            infoContainer.style.display = 'block';
            modal.setTitle('About this demo');
            modal.setContent(infoContainer);
            modal.open();
            modal.getModel().once('change:open', function () {
                mdlDialog.className = mdlDialog.className.replace(mdlClass, '');
            })
        });

        pn.addButton('options', {
            id: 'open-info',
            className: 'fa fa-question-circle',
            command: function () {
                editor.runCommand('open-info')
            },
            attributes: {
                'title': 'About',
                'data-tooltip-pos': 'bottom',
            },
        });
        const panelViews = pn.addPanel({
            id: 'views'
        });
        panelViews.get('buttons').add([{
            attributes: {
                title: 'Open Code'
            },
            className: 'fa fa-file-code-o',
            command: 'open-code',
            togglable: false, //do not close when button is clicked again
            id: 'open-code'
        }]);
        const panelViewsLeft = pn.addPanel({
            id: 'options'
        });
        panelViewsLeft.get('buttons').add([
            {
                attributes: {
                    title: 'Toggle Rulers'
                },
                context: 'toggle-rulers', //prevents rulers from being toggled when another views-panel button is clicked
                label: `<svg width="18" viewBox="0 0 16 16"><path d="M0 8a.5.5 0 0 1 .5-.5h15a.5.5 0 0 1 0 1H.5A.5.5 0 0 1 0 8z"/><path d="M4 3h8a1 1 0 0 1 1 1v2.5h1V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v2.5h1V4a1 1 0 0 1 1-1zM3 9.5H2V12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V9.5h-1V12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9.5z"/></svg>`,
                command: 'ruler-visibility',
                id: 'ruler-visibility'
            },
            {
                attributes: {
                    title: 'Export'
                },
                context: 'toggle-export', //prevents rulers from being toggled when another views-panel button is clicked
                // label: `<img src="./img/zip-export.svg" style="width: 18px;color: white;" alt=""/>`,
                label: `<svg fill="#000000" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
\t width="18" height="18" viewBox="0 0 550.801 550.801"
\t xml:space="preserve">
<g>
\t<g>
\t\t<path d="M475.095,131.992c-0.032-2.526-0.833-5.021-2.568-6.993L366.324,3.694c-0.021-0.034-0.053-0.045-0.084-0.076
\t\t\tc-0.633-0.707-1.36-1.29-2.141-1.804c-0.232-0.15-0.465-0.285-0.707-0.422c-0.686-0.366-1.393-0.67-2.131-0.892
\t\t\tc-0.2-0.058-0.379-0.14-0.58-0.192C359.87,0.114,359.047,0,358.203,0H97.2C85.292,0,75.6,9.693,75.6,21.601v507.6
\t\t\tc0,11.913,9.692,21.601,21.6,21.601H453.6c11.918,0,21.601-9.688,21.601-21.601V133.202
\t\t\tC475.2,132.796,475.137,132.398,475.095,131.992z M243.599,523.494H141.75v-15.936l62.398-89.797v-0.785h-56.565v-24.484h95.051
\t\t\tv17.106l-61.038,88.636v0.771h62.002V523.494z M292.021,523.494h-29.744V392.492h29.744V523.494z M399.705,463.44
\t\t\tc-10.104,9.524-25.069,13.796-42.566,13.796c-3.893,0-7.383-0.19-10.104-0.58v46.849h-29.352V394.242
\t\t\tc9.134-1.561,21.958-2.721,40.036-2.721c18.277,0,31.292,3.491,40.046,10.494c8.354,6.607,13.996,17.486,13.996,30.322
\t\t\tC411.761,445.163,407.479,456.053,399.705,463.44z M97.2,366.752V21.601h129.167v-3.396h32.756v3.396h88.28v110.515
\t\t\tc0,5.961,4.831,10.8,10.8,10.8H453.6l0.011,223.836H97.2z"/>
\t\t<path d="M359.279,413.87c-6.033,0-10.114,0.586-12.245,1.171v38.676c2.521,0.585,5.632,0.785,9.914,0.785
\t\t\tc15.736,0,25.46-7.979,25.46-21.378C382.408,421.063,374.045,413.87,359.279,413.87z"/>
\t\t<rect x="259.124" y="39.918" width="32.756" height="13.516"/>
\t\t<rect x="226.368" y="21.601" width="32.756" height="10.125"/>
\t\t<rect x="226.368" y="60.146" width="32.756" height="13.516"/>
\t\t<rect x="259.124" y="82.274" width="32.756" height="13.518"/>
\t\t<rect x="259.124" y="124.983" width="32.756" height="13.516"/>
\t\t<rect x="226.368" y="103.275" width="32.756" height="13.516"/>
\t\t<path d="M259.124,149.537c-23.193,0-34.225,18.792-34.225,41.99l-7.765,70.348c0,23.198,18.792,42.003,41.984,42.003
\t\t\tc23.19,0,41.974-18.805,41.974-42.003l-7.741-70.348C293.361,168.334,282.318,149.537,259.124,149.537z M273.04,285.431h-27.799
\t\t\tv-58.728h27.799V285.431z"/>
\t</g>
</g>
</svg>`,
                command: 'gjs-export-zip',
                id: 'export-visibility'
            },
        ]);

        // Add and beautify tooltips
        [['sw-visibility', 'Show Borders'], ['preview', 'Preview'], ['fullscreen', 'Fullscreen'],
            ['export-template', 'Export'], ['undo', 'Undo'], ['redo', 'Redo'],
            ['gjs-open-import-webpage', 'Import'], ['canvas-clear', 'Clear canvas']]
            .forEach(function (item) {
                pn.getButton('options', item[0]).set('attributes', {title: item[1], 'data-tooltip-pos': 'bottom'});
            });
        [['open-sm', 'Style Manager'], ['open-layers', 'Layers'], ['open-blocks', 'Blocks']]
            .forEach(function (item) {
                pn.getButton('views', item[0]).set('attributes', {title: item[1], 'data-tooltip-pos': 'bottom'});
            });
        var titles = document.querySelectorAll('*[title]');

        for (var i = 0; i < titles.length; i++) {
            var el = titles[i];
            var title = el.getAttribute('title');
            title = title ? title.trim() : '';
            if (!title)
                break;
            el.setAttribute('data-tooltip', title);
            el.setAttribute('title', '');
        }


        // Store and load events
        editor.on('storage:load', function (e) {
            console.log('Loaded ', e)
        });
        editor.on('storage:store', function (e) {
            console.log('Stored ', e)
        });


        // Do stuff on load
        editor.on('load', function () {
            var $ = grapesjs.$;

            // Show borders by default
            pn.getButton('options', 'sw-visibility').set({
                command: 'core:component-outline',
                'active': true,
            });

            // Show logo with the version
            var logoCont = document.querySelector('.gjs-logo-cont');
            document.querySelector('.gjs-logo-version').innerHTML = 'v' + grapesjs.version;
            var logoPanel = document.querySelector('.gjs-pn-commands');
            logoPanel.appendChild(logoCont);


            // Load and show settings and style manager
            var openTmBtn = pn.getButton('views', 'open-tm');
            openTmBtn && openTmBtn.set('active', 1);
            var openSm = pn.getButton('views', 'open-sm');
            openSm && openSm.set('active', 1);

            // Remove trait view
            pn.removeButton('views', 'open-tm');

            // Add Settings Sector
            var traitsSector = $('<div class="gjs-sm-sector no-select">' +
                '<div class="gjs-sm-sector-title"><span class="icon-settings fa fa-cog"></span> <span class="gjs-sm-sector-label">Settings</span></div>' +
                '<div class="gjs-sm-properties" style="display: none;"></div></div>');
            var traitsProps = traitsSector.find('.gjs-sm-properties');
            traitsProps.append($('.gjs-traits-cs'));
            $('.gjs-sm-sectors').before(traitsSector);
            traitsSector.find('.gjs-sm-sector-title').on('click', function () {
                var traitStyle = traitsProps.get(0).style;
                // var hidden = traitStyle.display == 'none';
                if (hidden) {
                    traitStyle.display = 'block';
                } else {
                    traitStyle.display = 'none';
                }
            });

            // Open block manager
            var openBlocksBtn = editor.Panels.getButton('views', 'open-blocks');
            openBlocksBtn && openBlocksBtn.set('active', 1);

            // Move Ad
            $('#gjs').append($('.ad-cont'));
        });

        setEditor(editor)
    }, []);

    async function greet() {
        // Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
        setGreetMsg(await invoke("greet", {name}));
    }

    return (
        <>
            <div>
                <div id="gjs" style={{height: 0, overflow: 'hidden'}}></div>
            </div>
        </>
    );
}

export default App;
